<template>
    <view class="page over-auto-y column">
        <hj-navbar title="续订房间" />
        <!-- 内容区 -->
        <view class="flex-auto w100 over-auto-y p-30">
            <!-- 订房信息 -->
            <RoomInfo :info="orderDetail" />
            <!-- 用户信息 -->
            <UserInfo :info="orderDetail" v-model:day="daysCount" @change="handleChange" />

            <view class="pt-30 pb-40 ft-24 t-9">
                <view class="mb-8">续订说明:</view>
                <view>
                    订单需等酒店确认后生效，订单确认结果以短信通知或者电话联系为准，如果订单不确认将全额退款至您的付款账户。
                </view>
            </view>
        </view>
        <!-- 底部 -->
        <PreFooter
            @submit="submit"
            :info="roomInfo.roomInfoPriceResp"
            :roomNum="orderDetail.roomCount"
            :checkOutDate="checkOutDate"
            :breakfastCount="orderDetail.breakfastCount"
        />
    </view>
</template>

<script setup>
/**
 * @description 预下单页面
 * @author yinzhi
 * @date 2025-05
 */
import { onLoad } from '@dcloudio/uni-app'
import { ref, defineComponent, computed } from 'vue'
import { logger } from '@/utils/log.js'
import PreFooter from './components/PreFooter.vue'
import RoomInfo from './components/RoomInfo.vue'
import UserInfo from './components/UserInfo.vue'
import dayjs from 'dayjs/esm/index'
import { getRoomDetailApi } from '@/libs/api/roomApi.js'
import { getOrderDetailApi, getCreateOrderApi, getPayOrderApi } from '@/libs/api/orderApi.js'
// 引入组件
defineComponent({
    components: {
        PreFooter,
        RoomInfo,
        UserInfo
    }
})
// 续租天数
const daysCount = ref(1)
// 原订单号
const orderNo = ref()
// 订单详情数据
const orderDetail = ref({})
// 是否可以点击
const isClick = ref(true)

// 初始化页面
onLoad(e => {
    // 从个人中心跳转的携带的参数 订单状态
    if (e.orderNo) {
        orderNo.value = e.orderNo
        getOrderDetail()
    }
})
const getOrderDetail = async () => {
    try {
        const data = await getOrderDetailApi({
            orderNo: orderNo.value
        })
        orderDetail.value = data || {}
        await getRoomDetails()
    } catch (error) {
        logger.error('[getOrderDetailApi] 获取订单详情失败:', error)
    }
}
const checkOutDate = computed(() => {
    return (
        dayjs(orderDetail.value.checkOutDate).add(daysCount.value, 'days').format('YYYY-MM-DD') ||
        ''
    )
})

// 房型详情
const roomInfo = ref({
    roomInfoPriceResp: {}
})
const stockNum = computed(() => roomInfo.value?.roomTypeInfoDetailResp?.stockNum || 0)
// 获取房型详情
const getRoomDetails = async () => {
    try {
        const data = await getRoomDetailApi({
            checkInDate: orderDetail.value.checkOutDate,
            checkOutDate: checkOutDate.value,
            hotelId: orderDetail.value?.hotelId || '',
            roomId: orderDetail.value.roomTypeId,
            roomNum: orderDetail.value.roomCount
        })
        roomInfo.value = data || { roomInfoPriceResp: {} }
    } catch (error) {
        logger.error('[getRoomDetails] 获取房型详情失败: ', error)
    }
}

// 加减变化
const handleChange = async e => {
    daysCount.value = e.value
    await getRoomDetails()
}

const requestPayment = data => {
    uni.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.packageValue,
        signType: data.signType,
        paySign: data.paySign,
        success: res => {
            uni.showToast({
                title: '支付成功',
                icon: 'none',
                mask: true
            })
            // 需要初始化加载一些订单列表的数据
            uni.$emit('initOrder', { isInit: true })
            let time = setTimeout(() => {
                uni.navigateBack({
                    delta: 1
                })
                clearTimeout(time)
            }, 1000)
        },
        fail: err => {
            isClick.value = true
            uni.$emit('initOrder', { isInit: true })
            uni.showToast({
                title: '已取消支付',
                icon: 'none',
                mask: true
            })
        }
    })
}

const payOrder = async orderNo => {
    try {
        const data = await getPayOrderApi({
            orderNo: orderNo,
            payBizType: 1, //1: 订单支付
            payWay: 1 //1: 微信支付
        })
        await requestPayment(data)
    } catch (error) {
        isClick.value = true
        logger.error('[getPayOrderApi] 唤起支付失败: ', error)
    }
}
// 提交订单
const submit = async () => {
    if (stockNum.value <= 0) {
        uni.showToast({
            title: '当前日期内该房型房源已售完，可到首页选择入住其他房型!',
            icon: 'none',
            duration: 2000
        })
        return
    }
    if (!isClick.value) return
    isClick.value = false
    try {
        const data = await getCreateOrderApi({
            arrivalStartTime: checkOutDate.value + ' 14:00:00', //预计到店时间(yyyy-MM-dd HH:mm:ss)
            checkInDate: orderDetail.value.checkOutDate,
            checkOutDate: checkOutDate.value,
            contactName: orderDetail.value.contactName,
            contactPhone: orderDetail.value.contactPhone,
            guestCount: orderDetail.value.maxGuests,
            hotelId: orderDetail.value.hotelId,
            orgOrderNo: orderNo.value,
            roomId: orderDetail.value.roomTypeId,
            roomNum: orderDetail.value.roomCount,
            isExtendedOrder: true
        })
        if (data.orderSuccess) {
            await payOrder(data.orderNo)
        } else {
            isClick.value = true
            uni.showToast({
                title: data.errorMsg,
                icon: 'none',
                mask: true
            })
        }
    } catch (error) {
        isClick.value = true
        logger.error('[getCreateOrderApi] 下单失败: ', error)
    }
}
</script>

<style scoped lang="scss">
:deep(.u-input) {
    padding-left: 0 !important;
    padding-right: 0 !important;
}
.page {
    background: $uni-bg-color-grey;
    width: 100vw;
    min-height: 100vh;
}
</style>
